package com.manor.dynamic.activity


import android.app.Activity
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.manor.dynamic.R
import com.manor.common.Constants
import com.manor.common.event.DynamicCommentEvent
import com.manor.common.utils.DpUtil
import com.manor.common.utils.KLog
import com.manor.common.utils.ScreenDimenUtil
import com.manor.common.utils.WordUtil
import com.manor.dynamic.adapter.DynamicImgAdapter
import com.manor.dynamic.bean.CommunityDynamicBean
import com.manor.dynamic.custorm.DynamicVideoViewContainer
import com.manor.dynamic.custorm.VideoPlayView
import com.manor.dynamic.event.DynamicDelEvent
import com.manor.dynamic.inter.VoicePlayCallBack
import com.manor.dynamic.views.AudioMp3View
import com.manor.dynamic.views.DynamicCommentViewHolder
import com.manor.im.utils.ImTextRender
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
import android.view.View as View1

/**
 * Created by debug on 2019/7/25.
 * 动态详情
 */

class DynamicDetailsActivity : AbsDynamicCommentActivity() {
    private var mDynamicBean: CommunityDynamicBean? = null
    private var mBigPlay: Boolean = false
    private var mDynamicId: String? = null
    private var mDynamicUid: String? = null
    private var isLoadVideo: Boolean = false
    private var isLoadImg: Boolean = false
    private var isLoadVoice: Boolean = false
    private var mVoicePlayView: AudioMp3View? = null
    private var mIsFromUserCenter: Boolean = false
    private var dynamicImgAdapter: DynamicImgAdapter? = null

    internal var is_true = false//是否在播放
    private val arrayList = ArrayList<String>()
lateinit var input : TextView

    internal var mBubble: AudioMp3View? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_dynamic_details
    }

    override fun main() {
        super.main()
        setTitle(WordUtil.getString(R.string.dynamic_details))

        mDynamicBean = intent.getSerializableExtra(Constants.DYNAMIC_BEAN) as CommunityDynamicBean
        mIsFromUserCenter = intent.getBooleanExtra(Constants.DYNAMIC_FROM_USER_CENTER, false)


        if (mDynamicBean == null) {
            return
        }
        mDynamicId = mDynamicBean?.id
        mDynamicUid = mDynamicBean?.uid
        input = findViewById<TextView>(R.id.input)
                findViewById<View1>(R.id.btn_voice).setOnClickListener(this)
        input.setOnClickListener(this)
        findViewById<View1>(R.id.btn_face).setOnClickListener(this)
        findViewById<View1>(R.id.title_right).visibility = View1.VISIBLE
        findViewById<View1>(R.id.title_right).setOnClickListener(this)

        mDynamicCommentViewHolder = DynamicCommentViewHolder(mContext, findViewById<View1>(R.id.container) as ViewGroup, mDynamicBean, mIsFromUserCenter)
        mDynamicCommentViewHolder.addToParent()

        if (mDynamicBean?.type == Constants.DYNAMIC_TYPE_VIDEO) {
            mPlayView = LayoutInflater.from(mContext).inflate(R.layout.dynamic_videoplay_view, null) as VideoPlayView
            mPlayView.setLargePlayCallback { large -> mBigPlay = large }
        }
        mVoicePlayCallBack = object : VoicePlayCallBack {
            override fun onPlayStart() {
                pauseDynamicVoice()
            }

            override fun onPlayResume() {
                pauseDynamicVoice()
            }

            override fun onPlayPause() {
                //resumeDynamicVoice();
            }

            override fun onPlayAutoEnd() {
                if (mDynamicCommentViewHolder != null) {
                    mDynamicCommentViewHolder.stopVoiceAnim()
                }
                // resumeDynamicVoice();
            }

            override fun onPlayEnd() {
                // resumeDynamicVoice();
            }
        }
        EventBus.getDefault().register(this)
    }

    fun setTextContext(msg: String) {
        input.setText(ImTextRender.renderChatMessage(msg))
    }

    fun loadImg(container: FrameLayout) {
        if (!isLoadImg) {
            isLoadImg = true
            container.visibility = View1.VISIBLE
            val view = LayoutInflater.from(mContext).inflate(R.layout.view_img_group, container, false)
            if (mDynamicBean?.thumbs?.size == 1) {
                val im_pic = view.findViewById<ImageView>(R.id.im_pic)
                Glide.with(mContext).load(mDynamicBean!!.thumbs[0])

                        .centerCrop()
                        .apply(RequestOptions().transform(CenterCrop(), RoundedCorners(DpUtil.dp2px(8))))
                        .into(im_pic)
                im_pic.visibility = View1.VISIBLE
                im_pic.setOnClickListener { lookImgs(mDynamicBean?.thumbs, 0) }
            } else {
                val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
                recyclerView.layoutManager = GridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false)
//              val decoration = ItemDecoration(mContext, 0x00000000, 3f, 3f)
//                decoration.isOnlySetItemOffsetsButNoDraw = true
                recyclerView.isNestedScrollingEnabled = false
  //              recyclerView.addItemDecoration(decoration)
                dynamicImgAdapter = DynamicImgAdapter(mContext)
                val imagess = ArrayList<String>()
                if(!TextUtils.isEmpty(mDynamicBean?.thumb)){
                    val split = mDynamicBean?.thumb?.split(";".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray()
                    imagess.addAll(Arrays.asList(*split!!))
                }
                dynamicImgAdapter?.setOnItemClickListener { url, position -> lookImgs(imagess, position) }
                dynamicImgAdapter?.setList(mDynamicBean?.thumbs)
                recyclerView.adapter = dynamicImgAdapter
            }
            container.addView(view)
        }
    }

    fun sotpall() {
        if (null != mBubble) {
            mBubble?.stopVoice()
        }
        if (null != mPlayView) {
            mPlayView.pausePlay()
            is_true = false
        }
    }

    fun loadVideo(container: FrameLayout) {
        if (!isLoadVideo) {
            isLoadVideo = true
            container.visibility = View1.VISIBLE
            val view = LayoutInflater.from(mContext).inflate(R.layout.view_video_group, container, false)
            val dynamicVideoViewContainer = view.findViewById<DynamicVideoViewContainer>(R.id.playViewContainer)
            val ivCover = view.findViewById<ImageView>(R.id.cover)
            val im_play = view.findViewById<ImageView>(R.id.im_play)
            container.isEnabled = false
            container.setOnClickListener {
                if (!is_true) {
                    is_true = true
                    im_play.visibility = View1.GONE
                    mPlayView.resumePlay()
                } else if (dynamicVideoViewContainer.hasPlayView()) {
                    im_play.visibility = View1.VISIBLE
                    mPlayView.pausePlay()
                    if (null != mBubble) {
                        mBubble?.stopVoice()
                    }
                    mBigPlay = true
                    (mContext as AbsDynamicActivity).addPlayerGroup(container, view, mPlayView)
                }
            }

            val mVideoLayoutParams = container.layoutParams as LinearLayout.LayoutParams
            mVideoLayoutParams.width = ScreenDimenUtil.getInstance().getScreenHeight() - DpUtil.px2dip(mContext, 32f)
            container.layoutParams = mVideoLayoutParams
            dynamicVideoViewContainer.setPlayEventListener(object : DynamicVideoViewContainer.PlayEventListener {
                override fun onStartPlay() {
                    KLog.e("tag", "onStartPlay")

                    if (ivCover != null && ivCover.visibility == View1.VISIBLE) {
                        ivCover.visibility = View1.INVISIBLE
                        im_play.visibility = View1.INVISIBLE
                    }
                }

                override fun onFirstFrame() {
                    KLog.e("tag", "onFirstFrame")
                    container.isEnabled = true
                    if (ivCover != null && ivCover.visibility == View1.VISIBLE) {
                        ivCover.visibility = View1.INVISIBLE

                    }
                }

                override fun onResumePlay() {
                    im_play.visibility = View1.GONE

                    KLog.e("tag", "onResumePlay")
                }

                override fun onPausePlay() {
                    im_play.visibility = View1.VISIBLE
                    KLog.e("tag", "onPausePlay")
                }

                override fun onPausePlay2() {
                    KLog.e("tag", "onPausePlay2")
                }

                override fun onRemoveView() {
                    KLog.e("tag", "onRemoveView")
                }

                override fun onVideoSize(width: Int, height: Int, onlyimg: Boolean) {
                    if (onlyimg) {
                        val mVideoLayoutParams = container.layoutParams as LinearLayout.LayoutParams
                        mVideoLayoutParams.width = width
                        mVideoLayoutParams.height = height
                        container.layoutParams = mVideoLayoutParams
                     //   container.isEnabled = true
                    } else {
                        val mVideoLayoutParams = container.layoutParams as LinearLayout.LayoutParams
                        mVideoLayoutParams.width = width
                        mVideoLayoutParams.height = height
                        container .layoutParams = mVideoLayoutParams
                     //   container.isEnabled = true
                    }
                    KLog.e("tag", "第一次加载后修改视频父布局的宽$width")
                }
                //                   if (onlyimg) {
                //                    LinearLayout.LayoutParams mVideoLayoutParams = (LinearLayout.LayoutParams) container.getLayoutParams();
                //                    mVideoLayoutParams.width = width;
                //                    mVideoLayoutParams.height = height;
                //                    container.setLayoutParams(mVideoLayoutParams);
                //                    container.setEnabled(true);
                //                }
                //                    if (!onlyimg) {
                //                    LinearLayout.LayoutParams mVideoLayoutParams = (LinearLayout.LayoutParams) container.getLayoutParams();
                //                    mVideoLayoutParams.width = DpUtil.dp2px(115);
                //                    mVideoLayoutParams.height = DpUtil.dp2px(200);
                //                    container.setLayoutParams(mVideoLayoutParams);
                //
                //                }
            })
            if (!dynamicVideoViewContainer.hasPlayView()) {
                dynamicVideoViewContainer.addPlayView(mPlayView)
                mPlayView.setDynamicBean(mDynamicBean)
                mPlayView.play()
                is_true = true

            }

            Glide.with(mContext).load(mDynamicBean?.video_thumb)
                    .apply(RequestOptions()
                            .transform(CenterCrop(), RoundedCorners(DpUtil.dp2px(8))
                            ))
                    .into(ivCover)
            container.addView(view)
        }
    }

    fun loadVoice(container: FrameLayout) {
        if (!isLoadVoice) {
            isLoadVoice = true
            container.visibility = View1.VISIBLE
            val view = LayoutInflater.from(mContext).inflate(R.layout.voice_play_view, container, false)
            val voicePlayView = view.findViewById<AudioMp3View>(R.id.voice_view)
            voicePlayView.mp3 = mDynamicBean?.voice.toString()
            voicePlayView.tag = mDynamicBean?.voice
            voicePlayView.setTextLeng(mDynamicBean?.length + "")
            mDynamicBean?.voice?.let { voicePlayView.playVoice(it) }
            voicePlayView.setOnClickListener {
                if (voicePlayView.isPlaying) {
                    voicePlayView.stopVoice()
                } else {
                    mDynamicBean?.voice?.let { it1 -> voicePlayView.playVoice(it1) }
                    if (null != mBubble) {
                        mBubble?.stopVoice()
                    }

                }
            }
            container.addView(view)
            mVoicePlayView = voicePlayView
        }
    }


    fun pauseDynamicVoice() {
        if (mDynamicBean?.type == Constants.DYNAMIC_TYPE_VOICE) {
            if (mVoicePlayView != null) {

            }
        }
    }

    fun resumeDynamicVoice() {
        if (mDynamicBean?.type == Constants.DYNAMIC_TYPE_VOICE) {
            if (mVoicePlayView != null) {

            }
        }
    }

    override fun onClick(v: View1?) {
        super.onClick(v)
        val i = v?.id
        if (i == R.id.input) {
            if (!TextUtils.isEmpty(mDynamicId) && !TextUtils.isEmpty(mDynamicUid)) {
                (mContext as AbsDynamicCommentActivity).openCommentInputWindow(false, mDynamicId, mDynamicUid, null,input.text.toString())
            }
        } else if (i == R.id.btn_face) {
            openFace()
        } else if (i == R.id.btn_voice) {
            (mContext as AbsDynamicCommentActivity).showVoiceViewHolder(mDynamicId, mDynamicUid, null)
        } else if (i == R.id.title_right) {
//            arrayList.clear()
//            arrayList.add("举 报")
//            arrayList.add("取 消")
//            showpop(v, arrayList, mDynamicBean?.id)
            (mContext as AbsDynamicActivity).setting(mDynamicBean)

        }

    }


    fun openFace() {
        if (!TextUtils.isEmpty(mDynamicId) && !TextUtils.isEmpty(mDynamicUid)) {
            (mContext as AbsDynamicCommentActivity).openCommentInputWindow(true, mDynamicId, mDynamicUid, null,input.text.toString())
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDynamicDel(e: DynamicDelEvent) {
        if (e.dynamicId == mDynamicId) {
            finish()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onDynamicComment(e: DynamicCommentEvent?) {
        if (mDynamicCommentViewHolder != null && e != null) {
            mDynamicCommentViewHolder.refreshComments(e.comments)
        }
    }

    fun playmp3(audioMp3View: AudioMp3View) {

        if (null == mBubble) {
            mBubble = audioMp3View
            mBubble?.playVoice(mBubble?.tag.toString() + "")

            if (null != mPlayView) {
                mPlayView.pausePlay()
                is_true = false
            }
            if (null != mVoicePlayView) {
                mVoicePlayView?.stopVoice()
            }
            return
        }
        if (mBubble!!.isPlaying) {
            mBubble?.stopVoice()
            if (mBubble?.tag != audioMp3View.tag) {
                mBubble = audioMp3View
                mBubble?.playVoice(mBubble?.tag.toString() + "")
                if (null != mPlayView) {
                    mPlayView.pausePlay()
                    is_true = false
                }
                if (null != mVoicePlayView) {
                    mVoicePlayView?.stopVoice()
                }

            }
        } else {
            mBubble = audioMp3View
            mBubble?.playVoice(mBubble?.tag.toString() + "")
            if (null != mPlayView) {
                mPlayView.pausePlay()
                is_true = false
            }
            if (null != mVoicePlayView) {
                mVoicePlayView?.stopVoice()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        if (this.isFinishing) {
            //进行数据操作及释放资源等操作
            if (mVoicePlayView != null) {
                mVoicePlayView?.release()
            }
            EventBus.getDefault().unregister(this)
        } else {
            if (mVoicePlayView != null) {
                mVoicePlayView?.resetView()
            }
        }
    }

    override fun onBackPressed() {
        if (isBackVideo) {
            videoBack()
        } else {
            mVoicePlayView?.release()
            mVoicePlayView?.resetView()
            mBubble?.release()
            mPlayView?.destroy()
            val intent = Intent()
            //把需要返回的数据存放在intent
            intent.putExtra("second", mDynamicCommentViewHolder.getmCommentString())
            intent.putExtra("islike", mDynamicCommentViewHolder.islike)
            intent.putExtra("likes", mDynamicCommentViewHolder.likes)
            intent.putExtra("isattent", mDynamicCommentViewHolder.isattent)
            setResult(Activity.RESULT_OK, intent)
            super.onBackPressed()
        }

    }

    companion object {

        fun forward(context: Context, dynamicBean: CommunityDynamicBean) {
            val intent = Intent(context, DynamicDetailsActivity::class.java)
            intent.putExtra(Constants.DYNAMIC_BEAN, dynamicBean)
            context.startActivity(intent)
        }

        fun forward(context: Context, dynamicBean: CommunityDynamicBean, isFromUserCenter: Boolean) {
            val intent = Intent(context, DynamicDetailsActivity::class.java)
            intent.putExtra(Constants.DYNAMIC_BEAN, dynamicBean)
            intent.putExtra(Constants.DYNAMIC_FROM_USER_CENTER, isFromUserCenter)
            context.startActivity(intent)
        }
    }
}
